from flask import Blueprint, g
from flask import request, jsonify
from flask import make_response, redirect
import json

from common.models.user import User
from common.libs.user.UserService import UserService
from common.libs.UrlManager import UrlManager
from common.libs.Helper import ops_render
from application import app

router_user = Blueprint('user_page', __name__)

@router_user.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return ops_render('user/login.html')

    result = {'code': 200, 'data': [], 'msg': '登入成功！'}
    login_name = request.values.get('login_name')
    login_pwd = request.values.get('login_pwd')
    is_empty = login_name and login_pwd

    if not is_empty:
        result['code'] = -1
        result['msg'] = "用户名或密码不能为空！"
        return jsonify(result)

    user = User.query.filter_by(login_name=login_name).first()
    if not user:
        result['code'] = -1
        result['msg'] = "用户名或密码输入错误！"
        return jsonify(result)
    if not user.login_pwd == UserService.genePwd(login_pwd, user.login_salt):
        result['code'] = -1
        result['msg'] = "用户名或密码输入错误！"
        return jsonify(result)

    if user.status == 0:
        result['code'] = -1
        result['msg'] = "登入账号异常，请联系管理员！"
        return jsonify(result)

    response = make_response(json.dumps(result))
    # max_age=60 * 60 * 24，cookie值有效期为1天
    response.set_cookie(app.config['AUTH_COOKIE_NAME'], '{}#{}'.format(UserService.geneAuthCode(user), user.uid))
    return response

@router_user.route('/edit', methods=['GET', 'POST'])
def edit():
    if request.method == 'GET':
        return ops_render('user/edit.html', {'current': 'edit'})

    nickname = request.values.get('nickname')
    email = request.values.get('email')
    result = {'code': 200, 'data': [], 'msg': '保存成功!'}

    if nickname is None or len(nickname) < 1:
        result['code'] = -1
        result['msg'] = '昵称不能为空!'
        return jsonify(result)

    if (email is None) or (len(email) < 6) or ('@' not in email) or ('.' not in email):
        result['code'] = -1
        result['msg'] = '请输入正确的邮箱格式!'
        return jsonify(result)

    # 修改内容同步到数据库
    user = g.current_user
    user.nickname = nickname
    user.email = email
    user.update()
    return jsonify(result)

@router_user.route('/reset_pwd', methods=['GET', 'POST'])
def reset_pwd():
    if request.method == 'GET':
        return ops_render('user/reset_pwd.html', {'current': 'reset-pwd'})

    old_password = request.values.get('old_password')
    new_password = request.values.get('new_password')
    result = {'code': 200, 'data': [], 'msg': '修改成功！'}
    user = g.current_user
    # 后端校验
    if UserService.genePwd(old_password, user.login_salt) != user.login_pwd:
        result['code'] = -1
        result['msg'] = '原密码输入错误'
        return jsonify(result)

    if old_password == new_password:
        result['code'] = -1
        result['msg'] = '旧密码不能与原密码重复哦！'
        return jsonify(result)

    # 修改同步数据库
    user.login_pwd = UserService.genePwd(new_password, user.login_salt)
    user.update()

    # 重置密码后，更新cookie值
    response = make_response(json.dumps(result))
    response.set_cookie(app.config['AUTH_COOKIE_NAME'], '{}#{}'.format(UserService.geneAuthCode(user), user.uid))
    return response

@router_user.route('/logout')
def logout():
    response = make_response(redirect(UrlManager.buildUrl('/user/login')))
    response.delete_cookie(app.config['AUTH_COOKIE_NAME'])  # 删除cookie
    return response
